<template>
	<view class="work_container">
		<navBar  title="进度填报" goBackUrl="/pages/homePage/homePage" @goBack="goBack"></navBar>
		<u-tabs :list="list" @click="fnTabClick" :scrollable='false'  :lineWidth="200" :inactiveStyle="{fontSize:'36rpx'}" :activeStyle="{color:'#2F80ED',fontWeight: '800',fontSize:'36rpx'}"></u-tabs>
		<view class="mater_right_box" v-show="tabIndex === 0">
			<scroll-view :scroll-y="true" :style="{height:scrollHeight}">
				<workGh @clickByGhItem="clickByGhItem" ref="ghRef" v-if="type ===  'gh' || type ===  'xgh'" :ghPmprId="ghPmprId"
					:ghObject="tempObj"></workGh>
				<workWrd ref="wrdRef" v-else :wrdObject="tempObj"></workWrd>
			</scroll-view>
			
		</view>

		<view class="mater_right_box" v-show="tabIndex === 1">
			<scroll-view :scroll-y="true" :style="{height:scrollHeight}">
				<new-material-reduce ref="newReduceRef"></new-material-reduce>
			</scroll-view>
		</view>	
		<u-modal :show="showPopup" :title="'提示'" :confirmText="'确认'" @confirm="popSubmit">
			<view class="slot-content">
					<u-icon name="error-circle-fill" color="#ffba00" size="26"></u-icon>
					<text>请及时在网页端上传质量管理相关资料(如第三方检测报告等)!</text>
			</view>
		</u-modal>
		<view class="footer-button">
			<view class="button-placeholder"></view>
			<view class="button-group">
				<button :loading="loading" @click="$u.throttle(fnStaging(1),1500)" class="button-warn">暂存</button>
				<button :loading="loading" @click="$u.throttle(fnStaging(0), 1500)"  class="button-primary">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapMutations } from 'vuex'
	import { getPicture, deleteImg, doc_deleteAttachs } from '@/api/doc.js'
	import newMaterialReduce from '@/subpackage-overhaul/pages/comprehensiveOverhaul/progressFilling/components/newMaterialReduce.vue'
	import workWrd from '@/subpackage-overhaul/pages/comprehensiveOverhaul/progressFilling/components/workLoadBywrd.vue'
	import workGh from '@/subpackage-overhaul/pages/comprehensiveOverhaul/progressFilling/components/wordLoadBygh.vue'
	import { uploadFile} from '@/utils/request'
	import { getEventShoppingCartList } from "@/api/emergency/emergencyDispatch.js";
	import { pmProcessReportSaveEx } from '@/api/comprehensive/comprehensive.js'
	import mixins from '@/utils/mixins.js'
	import {getToken} from '@/utils/auth.js'
	import { urlTobase64, uploadImageFromBase64} from '@/utils/imageOperation.js'
	// const each = (list = [], handler) => list.forEach(handler)
	export default {
		components: {
			workWrd, //微扰动组件
			workGh,
			newMaterialReduce,

		},
		mixins: [mixins],
		data() {
			return {
				loading:false,
				type: '', // 进度填报工作量类型 1钢环 2微扰动
				name: '工作量',
				list: [{
						name: '工作量'
					},
					{
						name: '材料消耗'
					}
				],
				tabIndex: 0,
				eventId: null, // 事件id
				stationList: [], // 基地列表数据
				shoppingCartNum: 0, // 购物车数量
				selectNum: 0, //已选
				selectCartList: [], //购物车数组
				retrunList: [],
				tempObj: {}, //表单对象
				ghPmprId: -1, //钢环回显的pmprId  用来请求已经填过的工序接口
				showPopup: false, //展示弹窗
				temporary_methods: '', //回显时暂存的工法
				temporaryForm: {}, //暂存的对象数据
				needEchoInfo: [], //需要回显的处理后的数组
				boxHeight: {
					box1: 45,
					box2: 40,
					box3: 50,
					box4: 35
				},
				clickOptionButton:false, //是否点击暂存或者提交按钮

			}
		},
		computed: {
			scrollHeight() {
				// #ifdef APP-PLUS || H5
					return `calc(100vh - ${44 + this.boxHeight.box2 + 80}px)`
				// #endif
				
				// #ifdef MP-WEIXIN
					return `calc(100vh - 220rpx - 120px)`
				// #endif
			}
		},
		onLoad(options) {
			// 获取上个页面表单传过来的数据
			if (options && options.preForm) {
				// console.log(JSON.parse(options.isContinue), '新增加的值')
				this.tempObj = JSON.parse(options.preForm)
				console.log(this.tempObj, '表单对象')
				this.type = this.tempObj.constructionMethod
				let bool = JSON.parse(options.isContinue)
				if(bool) {
					this.temporaryForm = JSON.parse(options.continueForm)
				}
				// console.log(this.tempObj,this.type,this.temporaryForm, '页面121行')
				//有暂存信息
				if (Object.keys(this.temporaryForm).length) {
					const dataInfo = this.temporaryForm
					this.ghPmprId = dataInfo.id //进度质量上报id
					console.log(dataInfo,'暂存信息')
					this.temporary_methods = dataInfo.constructionMethod
					// 钢环组装的数据格式
					if (this.temporary_methods === 'gh' || this.temporary_methods === 'xgh') {
						console.log(dataInfo.pmprWorkloadList, '原始数据')
						//组装数据 相同名字的工序环号组成数组
						const procedures = {}
						dataInfo.pmprWorkloadList.forEach(item => {
							const ele = procedures[item.steelRingProcedureName]
							if (ele) {
								ele.ringNumbers.push(item.ringNumber)
								ele.totalCount += item.workload ?? 0
							} else {
								procedures[item.steelRingProcedureName] = {
									...item,
									isHidden:item.isHidden && item.isHidden === 'true' ? true : false,
									ringNumbers: [item.ringNumber],
									isSplit:this.temporary_methods === 'gh' ? false : true,
									totalCount: item.workload ?? 0
								}
							}
						})
						// console.log(procedures, '处理后的数据')
						const objArray = []
						Object.keys(procedures).forEach(key => objArray.push({
							name: key,
							id: procedures[key].steelRingProcedureId,
							value: procedures[key]
						}))
						this.needEchoInfo = objArray
					}
					console.log(this.needEchoInfo,'数据161-')
				}
			}
		},

		async mounted() {
			// 计算scorll-view的高度 , 用100vh减去几个不滚动盒子的高度
			const query = uni.createSelectorQuery().in(this);
			query.select('.u-tabs').boundingClientRect(data => {
				this.boxHeight.box2 = data.height;
			}).exec();
			//放到这里的原因是onLoad通过refs的方式里面拿不到子组件里面的数据
			let subcomponent;
			console.log(this.temporary_methods, 'temporary_methods');
			if(this.temporary_methods) {
				if (this.temporary_methods === 'gh' || this.temporary_methods === 'xgh') {
					subcomponent = this.$refs.ghRef.rowBox
					// debugger
					this.needEchoInfo.forEach(async (item1, index1) => {
						if (!subcomponent[index1]) {
							 subcomponent.push({
								docId: '',
								fileListImg: [],
								processName: '',
								ringNumber: '',
								steelRingProcedureId: '',
								workload: 0
							})
						}
						//回显数据
						subcomponent[index1].processName = item1.name
						subcomponent[index1].steelRingProcedureId = item1.value.steelRingProcedureId
						subcomponent[index1].workload = item1.value.workload
						subcomponent[index1].isHidden = item1.value.isHidden
						subcomponent[index1].belong = item1.value.belong
						subcomponent[index1].grouping = item1.value.grouping
						subcomponent[index1].isSplit = item1.value.isSplit
						if (item1.value.docId) {
							subcomponent[index1].docId = item1.value.docId
							subcomponent[index1].fileListImg = await this.getItemImage(item1.value.docId)
						}
						subcomponent[index1].pmprId = item1.value.pmprId //编辑回显传回去的id
				
						//给回显的数据加个值，以区分新增
						subcomponent[index1].isEdit = true
						subcomponent[index1].ringNumber = item1.value.ringNumbers.join(',')
						
						for(let it of subcomponent) {
							if(it.fileListImg.length) {
								it.sourceImgIds = JSON.parse(JSON.stringify(it.fileListImg))
							}
						}
						this.copyInfo = [...subcomponent]
						console.log('钢环', subcomponent)
					})
				} else{
					subcomponent = this.$refs.wrdRef.rowBox
					// debugger
					console.log('微扰动204', subcomponent,this.temporaryForm.pmprWorkloadList)
					this.temporaryForm.pmprWorkloadList && this.temporaryForm.pmprWorkloadList.forEach(async (item2, index2) => {
						if (!subcomponent[index2]) {
							// debugger
							subcomponent.push({
								docId: '',
								fileListImg: [],
								processName: '',
								ringNumber: '',
								loweGroutingAmount: '',
								sludgeGroutingAmount:''
							})
						}
						//回显微扰动数据
						subcomponent[index2].processName = item2.ringNumber
						subcomponent[index2].steelRingProcedureId = item2.steelRingProcedureId
						subcomponent[index2].steelRingProcedureName = item2.steelRingProcedureName
						subcomponent[index2].workload = item2.workload
						subcomponent[index2].measureUnit = item2.unit || ''
						subcomponent[index2].ringNumber = item2.ringNumber
						subcomponent[index2].loweGroutingAmount = item2.loweGroutingAmount
						subcomponent[index2].sludgeGroutingAmount = item2.sludgeGroutingAmount
						subcomponent[index2].initialSettlementValue = item2.initialSettlementValue || ''
						subcomponent[index2].settlementValueBeforeGrouting = item2.settlementValueBeforeGrouting || ''
						subcomponent[index2].settlementValueAfterGrouting = item2.settlementValueAfterGrouting || ''
						if (item2.docId) {
							subcomponent[index2].docId = item2.docId
							subcomponent[index2].fileListImg = await this.getItemImage(item2.docId)
						}
						for(let it of subcomponent) {
							if(it.fileListImg.length) {
								it.sourceImgIds = JSON.parse(JSON.stringify(it.fileListImg))
							}
						}
						//给回显的数据加个值，以区分新增
						subcomponent.isEdit = true
						this.copyInfo = [...subcomponent]
						console.error('微扰动', subcomponent)
					})
				
				}
			}
			
			
			if(Object.keys(this.temporaryForm).length) {
				let editMater = this.$refs.newReduceRef.rowBox
				this.temporaryForm.pmprMaterialList.forEach((item3,index3) => {
					// console.log(!editMater[index3],'这是啥');
					if(!editMater[index3]) {
						editMater[index3] = {	}
					}
					//回显材料数据
					editMater[index3].processName = item3.parentTypeName + '-' + item3.deviceTypeName
					// editMater[index3].model = item3.specificationModel
					editMater[index3].model = item3.deviceTypeAttributeName
					editMater[index3].modelId = item3.deviceTypeAttributeId
					editMater[index3].deviceTypeName = item3.specificationModel
					editMater[index3].subDeviceTypeId = item3.deviceTypeId
					// editMater[index3].materiaId = item3.subDeviceTypeId
					editMater[index3].special = item3.parentTypeName + '-' + item3.deviceTypeName + '-' + item3.deviceTypeAttributeName
					editMater[index3].shelfLife = item3.num
					editMater[index3].unit = item3.unit
					editMater[index3].pmprId = this.ghPmprId
					editMater[index3].count = 1
					editMater.isEdit = true
				})
				// console.log(editMater,'编辑的材料消耗数据');
			}
		},
		methods: {
			getArrDifSameValue(arr1,arr2){
			    var result = [];
			    for(var i = 0; i < arr2.length; i++){
			        var obj = arr2[i];
			        var id = obj.id;
			        var isExist = false;
			        for(var j = 0; j < arr1.length; j++){
			            var aj = arr1[j];
			            var n = aj.id;
			            if(n == id){
			                isExist = true;
			                break;
			            }
			        }
			        if(!isExist){
			            result.push(obj);
			        }
			    }
			    return result;
			},
			getDifference(arr1, arr2) {
				return arr1.concat(arr2).filter((v, i, arr) => {
					return arr.indexOf(v) === arr.lastIndexOf(v)
				})
			},
			clickByGhItem(index) {
				this.$refs.ghRef.$refs.levelLinkage.open();
			},
			//tab切换 
			fnTabClick(val) {
				this.tabIndex = val.index
			},

			// 返回上一级
			goBack(url) {
				uni.switchTab({
					url: url
				})
			},

			// 点击按钮事件
			async fnStaging(num) {
				const ghEnum = ['gh', 'xgh']
				if(this.loading) return
				this.loading = true
				let that = this.tempObj
				let subFileData
				let refImpl
				if (ghEnum.includes(this.tempObj.constructionMethod)) {
					subFileData = this.$refs.ghRef.rowBox
					refImpl = this.$refs.ghRef
				} else{
					subFileData = this.$refs.wrdRef.rowBox
					refImpl = this.$refs.wrdRef
				}
				// console.log(subFileData,'绑定的表单数组');
				await refImpl.deleteFiles()
				await refImpl.uploadFileListAttach()
				// 表单校验
				for (let i = 0; i < subFileData.length; i++) {
					//如果是微扰动就不需要判断ringNumber
					if (this.tempObj.constructionMethod === 'wrd') {
						// console.log('微扰动得数据', subFileData)
						if (subFileData[i].processName === '' || subFileData[i].loweGroutingAmount === '' || subFileData[i].sludgeGroutingAmount === '') {
							this.loading = false
							return uni.showToast({
								title: `请填写完整第${i + 1}项的数据`,
								icon: 'none'
							})
						}
					} else if (ghEnum.includes(this.tempObj.constructionMethod)) {
						// console.log('钢环得数据', subFileData)
						if (subFileData[i].processName === '' || subFileData[i].ringNumber === '') {
							this.loading = false
							// `请填写完整第${i + 1}项的数据`
							return uni.showToast({
								title: `请填写完整数据`,
								icon: 'none'
							})
						}
					}
					if (subFileData[i].workload === '') {
						this.loading = false
						return uni.showToast({
							title: `请填写完整第${i + 1}项的数据`,
							icon: 'none'
						})
					}
				}
				// debugger
				let arr1 = subFileData.map(sub => ({
					pmprId: sub.pmprId || null,
					constructionMethod: that.constructionMethod, //施工工法（gh或者wrd）
					steelRingProcedureId: sub.steelRingProcedureId, //施工工序（来自钢环工序）
					steelRingProcedureName: ghEnum.includes(that.constructionMethod) ? sub.processName : sub.steelRingProcedureName, //施工工序名称，将来回显用
					workload:sub.workload || 0, //施工工序工作量系数
					ringNumber: ghEnum.includes(that.constructionMethod) ? sub.ringNumber.split(',') : sub
						.ringNumber, //环号或孔号
					loweGroutingAmount: ghEnum.includes(that.constructionMethod) ? undefined : Number(sub.loweGroutingAmount).toFixed(2) || 0, //水玻璃注浆量
					sludgeGroutingAmount: ghEnum.includes(that.constructionMethod) ? undefined : Number(sub.sludgeGroutingAmount).toFixed(2) || 0, //水泥浆注浆量
					docId: sub.docId, //施工图片	
					isHidden: !!sub.isHidden,
					belong:sub.belong || null,
					grouping:sub.grouping,
					unit:sub.measureUnit || '',
					initialSettlementValue: ghEnum.includes(that.constructionMethod) ? undefined : (sub.initialSettlementValue || undefined),
					settlementValueBeforeGrouting: ghEnum.includes(that.constructionMethod) ? undefined : (sub.settlementValueBeforeGrouting || undefined),
					settlementValueAfterGrouting: ghEnum.includes(that.constructionMethod) ? undefined : (sub.settlementValueAfterGrouting || undefined),
				}))
				// console.log(arr1, '数据arr1')
				// 接口需要单独的ringNumber对象
				let emptyList = []
				if (ghEnum.includes(this.tempObj.constructionMethod)) {
					arr1.map(ar => {
						ar.ringNumber.map(ri => {
							let obj = {
								pmprId: ar.pmprId,
								constructionMethod: ar.constructionMethod, //施工工法（gh或者wrd）
								steelRingProcedureId: ar.steelRingProcedureId || '', //施工工序（来自钢环工序）
								steelRingProcedureName: ar.steelRingProcedureName, //施工工序名称，将来回显用
								workload: ar.workload, //施工工序工作量系数
								ringNumber: ri, //环号或孔号
								groutingAmount: ar.groutingAmount, //注浆量
								docId: ar.docId, //施工图片
								isHidden: ar.isHidden,
								belong:ar.belong,
								grouping:ar.grouping,
								unit:ar.measureUnit || '',
								nameAndRing:`${ar.steelRingProcedureName}-${ri}`
							}
							emptyList.push(obj)
						})
					})
				} else{
					console.log('微扰动数据', arr1)
					arr1.forEach(it => {
						emptyList.push({
							...it
						})
					})
				}
				// console.log( emptyList,'数组167行')
				//这是第二版材料消耗页面的数据 重新映射成接口需要的入参格式
				let newList = this.$refs.newReduceRef.rowBox
				//防止两个规格型号都没有的情况
				for(let item of newList) {
					if(!item.special) {
						item.special = item.processName + '-' + item.subDeviceTypeId
					}
				}
				//通过数组对象中的count字段判断这个对象有没有值
				newList = newList.filter(it => it.count !== 0)
				console.log(newList, '材料原始数据');
				// if(newList.length > 1) {
					for(let i = 0; i < newList.length; i++) {
						if(newList[i].model === '') {
							this.loading = false
							return uni.showToast({
								title: `请填写第${i + 1}项的规格型号数据`,
								icon: 'none'
							})
						}
						if(newList[i].shelfLife <= 0) {
							this.loading = false
							return uni.showToast({
								title: `第${i + 1}项的消耗量应大于0`,
								icon: 'none'
							})
						}
					}
				// }
				// console.log(newList, 'newList');
				// 提交时判断数组中是否有重复的材料名称和材料型号(special值)
				const isRepeat = newList.some(r => newList.filter(r1 => r1.special === r.special).length > 1)
				if (isRepeat) {
					this.loading = false
					return uni.showToast({
						title: '存在重复的材料名称+材料型号!',
						icon: 'none'
					})
				}

				let newMap = newList.map(item => ({
					num: Number(item.shelfLife),
					unit:item.unit,
					deviceTypeId:item.subDeviceTypeId,
					deviceTypeAttributeId:item.modelId,
					subDeviceTypeName: item.processName.split("-")[0] || '',
					specificationModel: item.model,
					deviceTypeName:item.processName.split("-")[1] || '',
				})).filter(item => item.num !== 0)
				for(let key of emptyList) {
					let arr = ['xgh','gh','snwrd','swwrd']
					if((arr.includes(key.constructionMethod) && !key.ringNumber) || !key.steelRingProcedureId) {
						this.loading = false
						return uni.showToast({
							title:'请先填写完整信息',
							icon:'none'
						})
					}
				}
				if(!this.validNiuTui(emptyList)) {
					this.loading = false
					return uni.showToast({
						title:'同一个环号不能大小牛腿不能同时填报',
						icon:'none'
					})
				}
				let _params = {
					id: that.id,
					pmId: that.pmId, //项目管理id
					lineId: that.lineId, //线路id
					lineSiteSectionId: that.lineSiteSectionId, //站点或区间id
					lineSiteSectionName: that.lineSiteSectionName, //站点或区间名称
					lineSiteSectionType: that.lineSiteSectionType, //站点区间类型
					constructionDate: that.constructionDate, //施工日期
					laborNum: that.laborNum, //劳务人员数量
					constructionMethod: that.constructionMethod, //施工工法（gh或者wrd）
					//管理人员列表
					pmprManagePersonList: that.pmprManagePersonList,
					//工作量明细
					pmprWorkloadList: emptyList,
					//材料消耗列表
					pmprMaterialList: newMap,
					isTemporary: num, //暂存标识   1暂存  0提交
				}
				// console.log(this.loading, '接口入参！！！！')
				// return
				pmProcessReportSaveEx(_params).then(res => {
					this.clickOptionButton = true
					console.log(res, '保存接口')
					// 点击暂存跳转到填报记录页  点击提交弹出提示并且跳转到填报记录页
					if (res.status === 1 && res.success) {
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
						if (num === 1) {
							var pages = getCurrentPages();
							var prevPage = pages[pages.length - 2]; //上一个页面
							prevPage.$vm.getType({
								type: 1
							})
							uni.navigateBack();
							this.loading = false
						} else if (num === 0) {
							this.showPopup = true
							this.loading = false
						}
					}

				})
			},
			/**
			 * 同一个环号不能大小牛腿不能同时填报 ringNumber
			 * */
			validNiuTui(arr) {
				for(let item of arr) {
					//选择工序的id和grouping相同则为一级
					if(item.steelRingProcedureId === item.grouping) {
						for (let item2 of arr){
							//排除一级 并且找到当前一级的所有子级 并且相同环号相等则冲突
							if(item2.steelRingProcedureId !== item2.grouping&&item.steelRingProcedureId===item2.grouping&&item.ringNumber===item2.ringNumber){
								return false
							}
						}
					}
				}
				return true
			},
			
			//提交才会出现  弹窗确定按钮
			popSubmit() {
				this.showPopup = false
				var pages = getCurrentPages();
				var prevPage = pages[pages.length - 2]; //上一个页面
				prevPage.$vm.getType({
					type: 1
				})
				uni.navigateBack();
			},
			/**
			 * 获取到docId中的图片并且拼成网络路径格式
			 * @param {Number} docId
			 * @return {String} //拼好的网络路径格式
			 */
			async getItemImage(docId) {
				return await new Promise((resolve, reject) => {
					getPicture({
						docId
					}).then(res => {
						resolve(res.result.map(it => ({
							id:it.id,
							url: this.$config.IMG_FILE_URL + it.fileName
						})));
					}).catch(err => reject(err))
				})
			},

		}
	}
</script>

<style lang="scss" scoped>
	.work_container {
		height: 100%;
		width: 100%;
		/* #ifdef MP-WEIXIN */
			box-sizing: border-box;
			padding-top: 200rpx;
		/* #endif */
		
	}

	.item_top {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 20rpx;

		.top_reduce {
			// cursor: pointer;
			color: #16a7df;
		}
	}

	.content {
		padding: 35rpx;

		.value {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		.value-nav {
			position: relative;

			.day {
				position: absolute;
				top: 10rpx;
				right: -50rpx;
			}
		}

		.addArea {
			width: 100%;
			height: 96rpx;
			line-height: 96rpx;
			background: #F5F7FA;
			font-size: 32rpx;
			font-weight: bold;
			color: #445469;
			margin-top: 40rpx;
			text-align: center;
			margin-bottom: 40rpx;

			.image {
				width: 50rpx;
				height: 50rpx;
				margin-bottom: -13rpx;
			}
		}
	}

	.little_count {
		margin-top: 30rpx;
		text-align: right;
		padding-right: 20rpx;
	}

	.btn_box {
		height: 100rpx;

		.btn_group {
			display: flex;
			align-items: center;
			justify-content: space-between;
			// margin-top: 100rpx;
			position: fixed;
			bottom: 0;
			width: 100%;

		}
	}

	.value2 {
		display: flex;
		align-items: center;
		text-align: right;

		.none {
			flex: 1;
		}

	}

	.value-nav {
		position: relative;

		.day {
			position: absolute;
			top: 10rpx;
			right: -50rpx;
		}
	}

	.footer {
		position: relative;
		width: 100%;
		right: -60rpx;
		position: fixed;
		height: 35px;
		bottom: 45px;
		background-color: #fff;

		// height: 100rpx;
		.image {
			position: absolute;
			bottom: 0rpx;
			right: 140rpx;
			width: 60rpx;
			height: 60rpx;
		}

		.select {
			position: absolute;
			bottom: 6rpx;
			right: 60rpx;
			font-size: 32rpx;
		}

		.num {
			position: absolute;
			bottom: 24rpx;
			right: 120rpx;
			padding: 5rpx 15rpx;
			border-radius: 30rpx;
			background-color: #f43530;
			color: #fff;
			z-index: 1;
		}
	}

	/deep/ .u-form-item__body__right__content__slot {
		flex-direction: column;
	}

	/deep/ .define-block {
		display: block;
	}
	.mater_right_box {
		height: 100%;
		background-color: #f5f7fa
	}
</style>
